<!-- src/views/system/User.vue -->
<template>
  <div>
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="账号">
              <el-input
                  v-model="searchForm.username"
                  placeholder="请输入账号"
                  @keyup="handleKeyPress"
                  clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="姓名">
              <el-input
                  v-model="searchForm.realName"
                  placeholder="请输入姓名"
                  @keyup="handleKeyPress"
                  clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item>
              <el-button type="primary" @click="handleSearch" :loading="loading">
                <i class="el-icon-search"></i> 查询
              </el-button>
              <el-button @click="handleReset">
                <i class="el-icon-refresh"></i> 重置
              </el-button>
              <el-button type="primary" @click="handleEdit()">
                编辑
              </el-button>
              <el-button type="warning" @click="handleResetPassword()">
                重置密码
              </el-button>
              <el-button type="danger" @click="handleDelete()">
                删除
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 用户表格 -->
    <el-card class="table-card">
      <el-table
          :data="tableData"
          border
          v-loading="loading"
          element-loading-text="数据加载中..."
          @row-click="handleRowClick"
          :row-class-name="tableRowClassName"
      >
        <el-table-column label="序号" width="60" align="center">
          <template #default="scope">
            {{ (userStore.pageInfo.page - 1) * userStore.pageInfo.size + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="账号" prop="username" min-width="120"></el-table-column>
        <el-table-column label="姓名" prop="realName" min-width="100"></el-table-column>
        <el-table-column label="手机号" prop="mobile" width="120"></el-table-column>
        <el-table-column label="邮箱" prop="email" min-width="180"></el-table-column>
        <el-table-column label="用户类型" prop="userType" width="100" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.userType === 'ADMIN'" type="danger">管理员</el-tag>
            <el-tag v-else type="primary">普通用户</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="status" width="120" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.status" type="success">正常</el-tag>
            <el-tag v-else type="danger">禁用</el-tag>
          </template>
        </el-table-column>
        <!-- 删除状态列 -->
        <el-table-column label="删除状态" prop="isDelete" width="100" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.isDelete === 1" type="info">已删除</el-tag>
            <el-tag v-else type="success">未删除</el-tag>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <el-pagination
          v-if="userStore.pageInfo.total > 0"
          :current-page="userStore.pageInfo.page"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="userStore.pageInfo.size"
          :total="userStore.pageInfo.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          class="pagination"
      />

      <!-- 无数据提示 -->
      <el-empty
          v-if="tableData.length === 0 && !loading"
          description="暂无数据"
          class="empty"
      />
    </el-card>

    <!-- 编辑用户组件 -->
    <UserEdit ref="userEditRef" @success="handleEditSuccess"/>

    <!-- 重置密码对话框 -->
    <el-dialog
        title="重置密码"
        v-model="passwordDialogVisible"
        width="400px"
        :close-on-click-modal="false"
    >
      <el-form
          :model="passwordForm"
          :rules="passwordRules"
          ref="passwordFormRef"
          label-width="80px"
      >
        <el-form-item label="新密码" prop="password">
          <el-input
              v-model="passwordForm.password"
              type="password"
              placeholder="请输入新密码"
              show-password
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="passwordDialogVisible = false">取消</el-button>
        <el-button
            type="primary"
            @click="submitPasswordForm"
            :loading="passwordLoading"
        >
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue';
import { useUserStore } from '@/stores/userStore.js';
import UserEdit from '@/views/system/UserEdit.vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import http from "@/axios/index.js";

const userStore = useUserStore();

// 类型定义
interface SearchForm {
  username: string;
  realName: string;
}

const MESSAGE = {
  SELECT_USER: '请先选择一个用户',
  USER_DELETED: '该用户已被删除',
  DELETE_CONFIRM: (username: string) => `确定要删除用户 "${username}" 吗？`,
  DELETE_SUCCESS: '删除成功',
  DELETE_FAIL: '删除失败: ',
};

// 数据绑定
const tableData = ref([]);
const userEditRef = ref(null);
const loading = ref(false);
const selectedRow = ref<any>(null);

// 密码重置相关
const passwordDialogVisible = ref(false);
const passwordLoading = ref(false);
const passwordFormRef = ref(null);

const passwordForm = reactive({
  password: ''
});

const passwordRules = {
  password: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少6位', trigger: 'blur' }
  ]
};

// 搜索条件和分页信息
const searchForm = reactive<SearchForm>({
  username: '',
  realName: '',
});

// 获取用户列表数据
const fetchUserList = async () => {
  loading.value = true;

  // 确保分页参数有效，使用 page 而不是 pageNumber
  const params = {
    page: userStore.pageInfo.page && userStore.pageInfo.page > 0 ? userStore.pageInfo.page : 1,
    size: userStore.pageInfo.size && userStore.pageInfo.size > 0 ? userStore.pageInfo.size : 10,
    username: searchForm.username.trim(),
    realName: searchForm.realName.trim(),
    withDeleted: true,
    showDeleted: true
  };

  try {
    await userStore.getUserList(params);
    tableData.value = userStore.userList || [];
    selectedRow.value = null; // 清除选中行
  } catch (error) {
    console.error('获取用户列表失败:', error);

    // 更详细的错误处理
    let errorMsg = '未知错误';
    if (error.response) {
      switch (error.response.status) {
        case 500:
          errorMsg = '服务器内部错误';
          break;
        case 502:
        case 503:
        case 504:
          errorMsg = '系统繁忙，请稍后再试';
          break;
        default:
          errorMsg = error.response.data?.message || error.response.data?.msg || '请求失败';
      }
    } else if (error.request) {
      errorMsg = '网络连接异常，请检查网络';
    } else {
      errorMsg = error.message || errorMsg;
    }

    ElMessage.error(MESSAGE.DELETE_FAIL + errorMsg);
    tableData.value = [];
  } finally {
    loading.value = false;
  }
};

// 页面加载时获取第一页数据
onMounted(() => {
  // 确保初始分页参数有效
  if (!userStore.pageInfo.page || userStore.pageInfo.page <= 0) {
    userStore.pageInfo.page = 1;
  }
  if (!userStore.pageInfo.size || userStore.pageInfo.size <= 0) {
    userStore.pageInfo.size = 10;
  }

  // 确保 pageInfo.total 有默认值
  if (userStore.pageInfo.total === undefined || userStore.pageInfo.total === null) {
    userStore.pageInfo.total = 0;
  }

  fetchUserList();
});

// 搜索用户
const handleSearch = () => {
  userStore.pageInfo.page = 1; // 搜索时重置到第一页
  fetchUserList();
};

// 重置搜索
const handleReset = () => {
  searchForm.username = '';
  searchForm.realName = '';
  userStore.pageInfo.page = 1; // 重置时也重置到第一页
  fetchUserList();
};

// 处理分页变化
const handleCurrentChange = (page: number) => {
  userStore.pageInfo.page = page && page > 0 ? page : 1;
  fetchUserList();
};

// 处理每页条数变化
const handleSizeChange = (size: number) => {
  userStore.pageInfo.page = 1; // 重置到第一页
  userStore.pageInfo.size = size && size > 0 ? size : 10;
  fetchUserList();
};

// 编辑用户信息
const handleEdit = () => {
  if (!selectedRow.value) {
    ElMessage.warning(MESSAGE.SELECT_USER);
    return;
  }

  if (selectedRow.value.isDelete === 1) {
    ElMessage.warning(MESSAGE.USER_DELETED);
    return;
  }

  userEditRef.value.show(selectedRow.value);
};

// 重置密码
const handleResetPassword = () => {
  if (!selectedRow.value) {
    ElMessage.warning(MESSAGE.SELECT_USER);
    return;
  }

  if (selectedRow.value.isDelete === 1) {
    ElMessage.warning(MESSAGE.USER_DELETED);
    return;
  }

  // 显示密码重置对话框
  passwordForm.password = '';
  passwordDialogVisible.value = true;
};

// 提交密码表单
const submitPasswordForm = () => {
  passwordFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      passwordLoading.value = true;
      try {
        const data = {
          userId: selectedRow.value.id,
          password: passwordForm.password
        };

        // 调用重置密码接口
        await http.put('/api/user/updatePassword', data);
        ElMessage.success('密码重置成功');
        passwordDialogVisible.value = false;
      } catch (error) {
        console.error('密码重置失败:', error);

        // 更详细的错误处理
        let errorMsg = '未知错误';
        if (error.response) {
          errorMsg = error.response.data?.message || error.response.data?.msg || '密码重置失败';
        } else if (error.request) {
          errorMsg = '网络连接异常，请检查网络';
        } else {
          errorMsg = error.message || errorMsg;
        }

        ElMessage.error('密码重置失败: ' + errorMsg);
      } finally {
        passwordLoading.value = false;
      }
    }
  });
};

// 修改删除用户方法
const handleDelete = async () => {
  if (!selectedRow.value) {
    ElMessage.warning('请先选择一个用户');
    return;
  }

  if (selectedRow.value.isDelete === 1) {
    ElMessage.warning('该用户已被删除');
    return;
  }

  try {
    await ElMessageBox.confirm(
        `确定要删除用户 "${selectedRow.value.username}" 吗？`,
        '删除确认',
        {
          type: 'warning',
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }
    );

    // 调用删除接口
    await userStore.deleteUser(selectedRow.value.id);
    ElMessage.success('删除成功');

    // 直接更新本地数据，将用户标记为已删除
    selectedRow.value.isDelete = 1;

    // 更新表格中的数据
    const index = tableData.value.findIndex(item => item.id === selectedRow.value.id);
    if (index !== -1) {
      tableData.value[index] = {...selectedRow.value};
    }

    // 同时更新userStore中的数据，确保分页信息正确
    const storeIndex = userStore.userList.findIndex(item => item.id === selectedRow.value.id);
    if (storeIndex !== -1) {
      userStore.userList[storeIndex] = {...selectedRow.value};
    }

  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error);

      // 更详细的错误处理
      let errorMsg = '未知错误';
      if (error.response) {
        errorMsg = error.response.data?.message || error.response.data?.msg || '删除失败';
      } else if (error.request) {
        errorMsg = '网络连接异常，请检查网络';
      } else {
        errorMsg = error.message || errorMsg;
      }

      ElMessage.error('删除失败: ' + errorMsg);
    }
  }
};

// 按回车键触发搜索
const handleKeyPress = (event: KeyboardEvent) => {
  if (event.key === 'Enter') {
    handleSearch();
  }
};

// 编辑成功后刷新当前页数据
const handleEditSuccess = () => {
  ElMessage.success('用户信息更新成功');
  // 确保使用当前页的分页参数刷新数据
  fetchUserList();
};

// 处理行点击事件
const handleRowClick = (row: any) => {
  selectedRow.value = row;
};

// 表格行的类名处理
const tableRowClassName = ({ row }: { row: any }) => {
  if (row.isDelete === 1) return 'deleted-row';
  if (selectedRow.value && row.id === selectedRow.value.id) return 'selected-row';
  return '';
};
</script>

<style scoped>
.search-card {
  margin-bottom: 20px;
}

.table-card {
  min-height: 500px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.empty {
  padding: 100px 0;
}

:deep(.el-table__body tr:hover) {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  transform: scale(1.01);
  transition: all 0.3s ease;
  z-index: 1;
  position: relative;
}

:deep(.selected-row) {
  background-color: #e6f7ff;
  font-weight: bold;
}

:deep(.deleted-row) {
  background-color: #f5f7fa;
  color: #909399;
  text-decoration: line-through;
}
</style>
